/*
 * Copyright (c) 2011 Auzingers
 * Created by Oui-IT
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.auzingers.docsorganizer.gui.task;

import com.auzingers.docsorganizer.DocsOrganizerApplication;
import com.auzingers.docsorganizer.exception.DefaultExceptionHandler;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

/**
 * Base class for async tasks with a spinning progress wheel and default error handling.
 * @param <A> type of parameters
 * @param <B> type of progress
 * @param <C> type of result
 */
public abstract class AbstractSimpleAsyncTask<A, B, C> extends AsyncTask<A, B, C> {

    private static final String TAG = DocsOrganizerApplication.APP_TAG + ".AbstractSimpleAsyncTask";

    private ProgressDialog dialog = null;

    private Throwable exception = null;

    private String message;

    private Context ctx;

    /**
     * Constructor to create a new AbstractSimpleAsyncTask.
     * @param ctx current context
     * @param message message to display in progress dialog
     */
    public AbstractSimpleAsyncTask(Context ctx, String message) {
        this.message = message;
        this.ctx = ctx;
    }

    /**
     * This method must be overwritten in a subclass to perform the actual background task.
     * @param param parameters
     * @return result
     * @throws Exception on error
     */
    protected abstract C run(A... param) throws Exception;

    /**
     * Must be overwritten in subclass to do gui stuff after execution, i.e. update the listview.
     * @param result result of processing
     */
    protected abstract void postExecute(C result);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(ctx, "", message, true);
    }

    @Override
    protected final C doInBackground(A... param) {
        try {
            return run(param);
        } catch (Throwable ex) {
            exception = ex;
            return null;
        }
    }

    @Override
    protected final void onPostExecute(C result) {
        postExecute(result);
        dialog.dismiss();
        if (exception != null) {
            DefaultExceptionHandler.handleGuiException(ctx, TAG, exception);
        }
    }
}